package com.ruoyi.common.mqtts;

import com.ruoyi.project.stop.service.impl.MqttServerServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 项目启动 监听主题
 *
 */
@Slf4j
@Component
public class MqttClientListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private MqttServerServiceImpl mqttServerService;

    private volatile AtomicBoolean isInit=new AtomicBoolean(false);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            //防止重复触发
            if(!isInit.compareAndSet(false,true)) {
                return;
            }
            List<MqttServerEntity> mqttServerEntityList = mqttServerService.getMqttServerList();
            for (MqttServerEntity mqttServerDat:mqttServerEntityList) {
                MqttClientConnect mqttClientConnect = new MqttClientConnect();
                mqttClientConnect.setMqttClientId(mqttServerDat.getId());
                String host = "tcp://"+mqttServerDat.getServerHost()+":"+mqttServerDat.getServerPort();
                mqttClientConnect.setMqttClient(host, mqttServerDat.getClientId(), mqttServerDat.getUsername(), mqttServerDat.getPassword(), mqttServerDat.getClientCleanSession()==0?false:true, new MqttClientCallback(mqttServerDat.getId()));
                mqttClientConnect.sub(StringUtils.commaDelimitedListToStringArray(mqttServerDat.getClientTopic()));
                MqttClientConnect.mqttClients.put(mqttServerDat.getId(), mqttClientConnect);
                log.info("{}--连接成功！！订阅主题--{}", mqttServerDat.getId(), mqttServerDat.getClientTopic());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
